package com.caochenlei.tree.ufs.version3;

public class UnionFindSets {
    private int[] eleAndGroup;
    private int count;
    private int[] eleAndCount;

    public UnionFindSets(int N) {
        this.count = N;
        this.eleAndGroup = new int[N];
        for (int i = 0; i < eleAndGroup.length; i++) {
            eleAndGroup[i] = i;
        }
        this.eleAndCount = new int[N];
        for (int i = 0; i < eleAndCount.length; i++) {
            eleAndCount[i] = 1;
        }
    }

    //获取并查集中有多少分组
    public int count() {
        return count;
    }

    //元素p所在分组的标识符
    public int find(int p) {
        while (true) {
            if (p == eleAndGroup[p]) {
                return p;
            }
            p = eleAndGroup[p];
        }
    }

    //查询元素p和元素q是否属于同一组
    public boolean connected(int p, int q) {
        return find(p) == find(q);
    }

    public void union(int p, int q) {
        //找到p元素和q元素所在组对应的树的根结点
        int pRoot = find(p);
        int qRoot = find(q);
        //如果p和q已经在同一分组，则不需要合并了
        if (pRoot == qRoot) {
            return;
        }
        //如果p和q不在一组，只需要让小树并入大树
        if (eleAndCount[pRoot] < eleAndCount[qRoot]) {
            eleAndGroup[pRoot] = qRoot;
            eleAndCount[qRoot] += eleAndCount[pRoot];
        } else {
            eleAndGroup[qRoot] = pRoot;
            eleAndCount[pRoot] += eleAndCount[qRoot];
        }
        //组的数量-1
        this.count--;
    }
}
